<?php

namespace app\api\controller;

use app\api\model\ThirdbindModel;
use app\api\model\UserModel;
use app\common\controller\Api;
use app\common\sendmsg\SendM;
use fast\Random;
use think\Cache;
use think\Cookie;
use think\Db;
use think\exception\PDOException;
use think\Request;

/**
 * 会员接口
 */
class User extends Api
{
    protected $noNeedLogin = '*';
    protected $noNeedRight = '*';

    // 前台用户登录
    public function Login()
    {
        $data = input('param.');
        $validate =Validate('LoginValidate');
        if(!$validate->scene('login')->check($data)){
            return json(['code'=>0,'msg'=>$validate->getError()]);
        }
        $res = Db::name('user')
            ->field('id,tel,password,username,headimg')
            ->where('tel',$data['tel'])->find();
        if ($res){
            if ($res['password']!==md5($data['password'])){
                $this->error('密码不正确');
            }else{
                //登录成功后 颁发临牌
                $token = Random::uuid();
                $res['token'] = $token;
                \app\common\library\Token::set($token,$res['id']);
                unset($res['password'],$res['id']);
                $this->success('登陆成功',$res);
            }
        }else{
            $this->error('该账户还未注册');
        }
    }

    // 注册
    public function registe()
    {
        $param = input('param.');
        $validate = validate('LoginValidate');
        if  (!$validate->scene('registe')->check($param)){
            $this->error($validate->getError());
        }
        $rand=Cache::store('redis')->get($param['tel']);
        if ($param['verify']==$rand){
            $info['tel']=$param['tel'];
            $info['password']=hash('md5',$param['password']);
            $info['headimg']='http://video.qilinxuan.net/upload/image/20181109/user.jpg';//默认头像
            $info['type']=1;//固定默认用户权限
            $info['username']='hlb_'.$info['tel'];
            $info['content']='这个人很懒~,什么都没留下..';
            $result = UserModel::create($info);
            if ($result){
                $this->success('注册成功');
            }else{
                $this->error('注册失败');
            }
        }else{
            $this->error('验证码不正确');
        }

    }

    // 第三方绑定登录
    public function third_bind()
    {
        $info = input('param.');
        $validate =Validate('LoginValidate');
        if(!$validate->scene('third_bind')->check($info)){
            $this->error($validate->getError());
        }
        // 判断是否绑定账号
        $tel = ThirdbindModel::getUserBind($info['openid']);
        if  ($tel){
            $user = UserModel::getUserInfoBytel($tel['tel']);
            unset($user['id']);
            $user['token'] = Random::uuid();
            \app\common\library\Token::set($user['token'],$tel['id']);
            unset($user['id']);
            $this->success('登陆成功',$user);
        }else{
            $this->error('未绑定手机');
        }
    }

    // 绑定手机号码
    public function bindTel()
    {
        $data = input('param.');
        $code = Cache::store('redis')->get($data['tel'].'rand');
        $validate = validate('LoginValidate');
        if (!$validate->scene('tel')->check($data)){
            $this->error(0,'',$validate->getError());
        }
        if ($data['code'] == $code){//验证码通过,跳转到设置密码页面
            $this->success(1,null,'验证通过');
        }else{
            $this->error(0,'','验证码不正确');
        }
    }
    // 第三方登录 手机验证成功后 判断该手机号码是否已经注册
    public function ishasTel()
    {
        $data = input('param.');
        $userinfo = UserModel::getUserInfoBytel($data['tel']);
        if (!$userinfo){
            $this->error('未绑定手机号');
        }else{
            $thirdarr = ['type'=>$data['thirdbase'],
                'nickname'=>$data['nickname'],'headimgurl'=>$data['headimgurl'],
                'tel'=>$data['tel'],'openid'=>$data['openid']];
            ThirdbindModel::create($thirdarr);
            $userinfo['token'] = Random::uuid();
            \app\common\library\Token::set($userinfo['token'],$userinfo['id']);
            unset($userinfo['id']);
            $this->success('登陆成功',$userinfo);
        }
    }

    public function sendverify()
    {
        $param=input('param.');
        $validate = validate('LoginValidate');
        if  (!$validate->scene('tel')->check($param)){
            $this->error($validate->getError());
        }
        if (Cookie::has('yzm')){
            $this->error('操作频繁,请稍后再试');
        }else{
            Cookie::set('yzm','setTime',60);
        }
        Cache::inc(\request()->ip());
        if (Cache::get(\request()->ip())>10){
            Cache::set(\request()->ip(),Cache::get(\request()->ip()),5*3600);
            $this->error('操作次数过多,请稍后再试');
        }
        $send = new SendM();
        $rand = rand(1000,9999);
        Cache::store('redis')->set($param['tel'],$rand,300);
        $data='【火龙宝】您的验证码是：'.$rand.'，请在5分钟内输入，如非本人操作请忽略。';
        $status = $send->sendVertify($data,$param['tel']);
        $status=json_decode($status,true);
        if (!$status['status']=='success'){
            $this->error('获取短信验证码失败');
        }else{
            $this->success('发送成功');
        }


    }


    // 第三方登录 绑定成功后 为账户设置密码
    public function setPassword()
    {
        $data = input('param.');
        $thirdarr = ['type'=>$data['thirdbase'],'tel'=>$data['tel'],'headimgurl'=>$data['headimgurl'],'nickname'=>$data['nickname'],'openid'=>$data['openid'],'create_time'=>time()];
        Db::startTrans();
        try{
            $userarr = ['tel'=>$data['tel'],'password'=>hash('md5',$data['password']),'headimg'=>'http://video.qilinxuan.net/upload/image/20181109/user.jpg','create_time'=>time(),'username'=>'hlb_'.$data['tel'],'content'=>'这个人很懒~,什么都没留下..'];
            $userid = Db::name('user')->insertGetId($userarr);
            unset($userarr['password']);
            unset($userarr['create_time']);
            $userarr['id'] = $userid;
            Db::name('third_bind')->insert($thirdarr);
            Db::commit();
            $userarr['token'] = Random::uuid();
            \app\common\library\Token::set($userarr['token'],$userid);
            $this->success('绑定成功',$userarr);
        }catch (PDOException $e){
            Db::rollback();
            $this->error('绑定失败');
        }
    }

    // 忘记密码
    public function iuserReset(Request $request)
    {
        $param= $request->param();
        $validate = validate('LoginValidate');
        if  (!$validate->scene('tel')->check($param)){
            $this->error($validate->getError());
        }
        $res=Db::name('user')->field('tel,password')->where('tel',$param['tel'])->find();
        if ($res){
            $rand=Cache::store('redis')->get($res['tel'].'rand');
            if ($param['verify']!=$rand){
                $this->error('验证码不正确');
            }
            try{
                $data=md5($param['password']);
                Db::name('user')->where('tel',$res['tel'])->setField('password',$data);
                $this->success('密码重置成功');
            }catch(\Exception $e){
                $this->error($e->getMessage());
            }
        }else{
            $this->error('账户不存在');
        }
    }


}
